package com.kchouse.mine;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.CashCouponItem;
import com.kchouse.bean.MineCouponItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class MineCouponsActivity extends BaseActivity implements View.OnClickListener {

    private MineCouponsActivity mContent;
    //声明pst的标题
    private TextView tv_title;
    private ImageView iv_back;
    private RadioGroup rg_item;
    private RadioButton rb_item1;
    private RadioButton rb_item2;
    private ListView lv_item;
    private ArrayList<CashCouponItem> listcashcoupon = new ArrayList<>();
    private ArrayList<MineCouponItem> listcoupon = new ArrayList<>();
    private TextView tv_userecord;
    private Intent intent;
    private boolean isCash = true;//当前是否是现金券
    private int cashNum;//现金券数量
    private ListView lv_item2;
    private MineCashCouponsAdapter cashadpter;
    private MineCouponsAdapter coupadapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_coupons);

        mContent = this;
        intiData();
        intiView();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("我的卡券");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);


        lv_item = (ListView) findViewById(R.id.lv_item);
        cashadpter= new MineCashCouponsAdapter();
        lv_item.setAdapter(cashadpter);
        lv_item2 = (ListView) findViewById(R.id.lv_item2);
        coupadapter=new MineCouponsAdapter();
        lv_item2.setAdapter(coupadapter);
        tv_userecord = (TextView) findViewById(R.id.tv_userecord);
        tv_userecord.setOnClickListener(this);
        intiRG();
    }

    /**
     * 初始化单选框
     */
    private void intiRG() {
        rg_item = (RadioGroup) findViewById(R.id.rg_item);
        rb_item1 = (RadioButton) findViewById(R.id.rb_item1);
        rb_item1.setChecked(true);
        rb_item2 = (RadioButton) findViewById(R.id.rb_item2);
        rg_item.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_item1) {
//                    ToastUtils.getInstanc(mContent).showToast("现金券");
//                    cashadpter.notifyDataSetChanged();
                    lv_item.setVisibility(View.VISIBLE);
                    lv_item2.setVisibility(View.GONE);
                    isCash = true;
                } else {
//                    ToastUtils.getInstanc(mContent).showToast("优惠券");
//                    lv_item.setAdapter();
                    lv_item.setVisibility(View.GONE);
                    lv_item2.setVisibility(View.VISIBLE);
                    isCash = false;
                }
            }
        });
    }


    private void intiData() {

        intent = getIntent();
        GetMineCashCoupons();
        GetMineCoupons();
    }


    /**
     * 获取我的优惠券
     */
    private void GetMineCoupons() {
        String url = API.GetMineCoupons + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("token", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    listcoupon.addAll(JSONObject.parseArray(datastr, MineCouponItem.class));
//                    lv_item.setAdapter(new MineCouponsAdapter());
                    coupadapter.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")||data.getString("code").equals("400")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 获取我的现金券
     */
    private void GetMineCashCoupons() {
        String url = API.GetMineCashCoupons + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("token", MineFragment.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    CashCouponItem data = JSONObject.parseObject(datastr, CashCouponItem.class);
                    if (data.getNum() != 0) {
                        listcashcoupon.add(data);
//                        lv_item.setAdapter(new MineCashCouponsAdapter());
                        cashadpter.notifyDataSetChanged();
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")||data.getString("code").equals("400")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    class MineCashCouponsAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listcashcoupon.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CashCouponItem item = listcashcoupon.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_cashcoupon_item, null);
            ImageView iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
            Picasso.with(mContent).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_icon);
//            TextView tv_name= (TextView) view.findViewById(R.id.tv_name);
//            tv_name.setText(item.getCashTemplateName());
            TextView tv_num = (TextView) view.findViewById(R.id.tv_num);
            cashNum = item.getNum();
            tv_num.setText("剩余数量：" + item.getNum()+"张");
            return view;
        }
    }

    class MineCouponsAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listcoupon.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

//            CouponItem item = listcoupon.get(position);
            MineCouponItem item = listcoupon.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_coupons_item, null);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_name.setText(item.getCouponTemplateName());
            TextView tv_time = (TextView) view.findViewById(R.id.tv_time);
            tv_time.setText("有效至："+item.getEndTime());
            TextView tv_merchantName = (TextView) view.findViewById(R.id.tv_merchantName);
            tv_merchantName.setText(item.getMerchantName());
            TextView tv_inventory = (TextView) view.findViewById(R.id.tv_inventory);
            tv_inventory.setText("剩余数量："+item.getRemain()+"张");
            ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);
            Picasso.with(mContent).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_item);
            TextView tv_distance = (TextView) view.findViewById(R.id.tv_distance);
            tv_distance.setVisibility(View.GONE);

//            MineCouponItem item = listcoupon.get(position);
//            View view = getLayoutInflater().inflate(R.layout.lv_cashcoupon_item, null);
//            TextView tv_num = (TextView) view.findViewById(R.id.tv_num);
//            tv_num.setText("剩余数量："+item.getRemain()+"张");
//            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
//            tv_name.setText(item.getCouponTemplateName());
//            TextView tv_merchantName = (TextView) view.findViewById(R.id.tv_merchantName);
//            tv_merchantName.setText(item.getMerchantShortName());
//            ImageView iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
//            Picasso.with(mContent).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_icon);
//            TextView tv_time = (TextView) view.findViewById(R.id.tv_time);
//            tv_time.setText("有效期:至"+item.getEndTime());
            return view;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_userecord://现金券使用记录

                intent.putExtra("cashNum", cashNum);
                intent.putExtra("isCash", isCash);
                intent.setClass(mContent, UserecordActivity.class);
                startActivity(intent);
                break;
        }
    }
}
